﻿using HomeWork911.Api.Read.Appliaction.Commond;
using HomeWork911.Api.Read.Dto;
using HomeWork911.Domain;
using HomeWork911.ErrorCode;
using HomeWork911.infrastrunceture;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace HomeWork911.Api.Read.Appliaction.CommondHandler
{
    public class LoginCommondHandler : IRequestHandler<LoginCommond, ApiResult<LoginDto>>
    {
        private readonly IBaseIRepository<Role> role;
        private readonly IBaseIRepository<User> user;   
        private readonly IBaseIRepository<RoleUser> roleUser;

        public LoginCommondHandler(IBaseIRepository<Role> role, IBaseIRepository<User> user, IBaseIRepository<RoleUser> roleUser)
        {
            this.role = role;
            this.user = user;
            this.roleUser = roleUser;
        }

        public Task<ApiResult<LoginDto>> Handle(LoginCommond request, CancellationToken cancellationToken)
        {
            ApiResult<LoginDto> result = new ApiResult<LoginDto>();
            result.Code=ApiEnum.登录成功;
            result.Msg = ApiEnum.登录成功.ToString();
            var list = from a in user.GetAll()
                       join b in roleUser.GetAll() on a.UserId equals b.UserId
                       join c in role.GetAll() on b.RoleId equals c.RoleId
                       where a.UserName == request.UserName
                       select new LoginDto()
                       {
                           UserId = a.UserId,
                           UserName=a.UserName,
                           UserNikename=a.UserNikename,
                           Password = a.Password,
                           RoleId=c.RoleId,
                           RoleName=c.RoleName
                       };
            var entity=list.FirstOrDefault();
            if (entity == null)
            {
                result.Code = ApiEnum.登录失败;
                result.Msg = ApiEnum.登录失败.ToString()+"用户名称不存在";
                return Task.FromResult(result);
            }    
            if(entity.Password!=request.Password)
            {
                result.Code = ApiEnum.登录失败;
                result.Msg = ApiEnum.登录失败.ToString() + "密码错误";
                return Task.FromResult(result);
            }
            entity.Token= CreateTokenString(entity);
            result.data = entity;
            return Task.FromResult(result);

        }
        /// <summary>/// 生成 JWT Token（令牌）/// </summary>/// <returns></returns>
        private string CreateTokenString(LoginDto login)
        {
            //私钥
            var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            var claims = new[]
            {
                new Claim("RoleId",login.RoleId.ToString()),
                new Claim("UserNikename",login.UserNikename),
                new Claim("UserId",login.UserId.ToString())
            };
            // 生成Token
            var token = new JwtSecurityToken(
                issuer: "BeiJingBW",
                audience: "BeiJingBW",
                claims: claims,
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }
    }
}
